﻿package com.eitb.programas.olentzero09.objetos{
	import flash.events.*;
	import flash.display.*;

	import com.eitb.util.*;
	import com.eitb.programas.olentzero09.*;
	import com.eitb.programas.olentzero09.events.*;

	public class Palote extends Sprite {
		private static const gravedad:Number=0.001;
		private var velocidad:Number;
		private var rotacion:Number;
		private var viento:Number;
		private var limites:Object;


		public function Palote():void {
			this.velocidad=0;
			this.rotacion = (Math.random()-0.8);
			this.viento = (Math.random()*2-1);
			this.scaleX=.25;
			this.scaleY=.25;
			this.addEventListener(Event.ENTER_FRAME, this.onEnterFrame);
		}

		public function initLimites(limites:Object):void {
			this.limites=limites;
		}

		public function init():void {
			this.x = Math.random() * this.limites.xMax;
			this.y=this.limites.y;
		}

		public function onEnterFrame(evt:Event):void {
			var espacio:Number = this.velocidad + Palote.gravedad * 0.5;
			this.y+=espacio;
			this.velocidad=espacio;
			this.rotation+=this.rotacion;
			this.x+=this.viento;
			this.rotation+=this.rotacion;
			if (this.isOut()) {
				this.setInBounds();
				this.viento = -(this.viento);
			} else if (this.isMuerto()) {
				this.finalize();
			}
		}

		private function isMuerto():Boolean {
			return (this.y > this.limites.yMax);
		}

		private function isOut():Boolean {
			return (this.x < this.limites.x) || (this.x > this.limites.xMax);
		}

		private function setInBounds():void {
			if (this.x<this.limites.x) {
				this.x=this.limites.x;
			}
			if (this.x>this.limites.xMax) {
				this.x=this.limites.xMax;
			}
		}

		public function finalize():void {
			try {
				this.removeEventListener(Event.ENTER_FRAME, this.onEnterFrame);
				this.parent.removeChild(this);
			} catch (e:Error) {
				trace(e);
			}
		}

		public function colision():void {
			this.parent.dispatchEvent(new OlentzeroEvent(OlentzeroEvent.COLISION, {colision:"palote", x:this.x , y:this.y}));
			this.finalize();
		}
	}
}